package com.chaofan.authsso.clientweb;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chaofan.authsso.client.AuthSsoClient;
import com.chaofan.authsso.client.common.Constant;
import com.chaofan.authsso.client.common.SsoRestfulMessage;
import com.chaofan.authsso.client.properties.SsoRegisterProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Author: Chaofan
 * Date: 2020/6/10 13:14
 * email: chaofan2685@qq.com
 */
@RestController
public class TestController {

    @Autowired
    AuthSsoClient authSsoClient;

    @Autowired
    SsoRegisterProperties properties;

    @GetMapping(value = "/api/getUserInfo")
    public SsoRestfulMessage getUserInfo(){
        SsoRestfulMessage ssoRestfulMessage = new SsoRestfulMessage();
        String resultJson = HttpUtil.get(properties.getHost()+"/api/getUserInfo?token="+authSsoClient.token());
        JSONObject jsonObject = JSONUtil.parseObj(resultJson);
        if (Constant.SUCCESS.intValue() == jsonObject.getInt("code").intValue()){
            User user = jsonObject.get("data",User.class);
            ssoRestfulMessage.setCode(Constant.SUCCESS);
            ssoRestfulMessage.setMessage("成功");
            ssoRestfulMessage.setData(user.getNickname());
        }else {
            ssoRestfulMessage.setCode(Constant.INTERNAL_SERVER_ERROR);
            ssoRestfulMessage.setMessage(jsonObject.getStr("message"));
        }
        return ssoRestfulMessage;
    }

    @GetMapping(value = "/api/logout")
    public SsoRestfulMessage logout(){
        SsoRestfulMessage ssoRestfulMessage = new SsoRestfulMessage();
        if (authSsoClient.logout()){
            ssoRestfulMessage.setCode(Constant.SUCCESS);
            ssoRestfulMessage.setMessage("成功");
        }else {
            ssoRestfulMessage.setCode(Constant.INTERNAL_SERVER_ERROR);
            ssoRestfulMessage.setMessage("退出失败");
        }
        return ssoRestfulMessage;
    }



}
